package cn.yqx.bankshop.order.controller;

import brave.Request;
import cn.yqx.bankshop.order.page.PageRequest;
import cn.yqx.bankshop.order.page.PageResult;
import cn.yqx.bankshop.order.pojo.BuOrder;
import cn.yqx.bankshop.order.pojo.BuOrderAssess;
import cn.yqx.bankshop.order.pojo.BuOrderTransactRecord;
import cn.yqx.bankshop.order.service.GoodsService;
import cn.yqx.bankshop.order.service.LogisticsService;
import cn.yqx.bankshop.order.service.OrderService;

import cn.yqx.bankshop.order.service.UserService;
import cn.yqx.bankshop.remote.LogisticsRemote;
import cn.yqx.bankshop.result.Result;
import cn.yqx.bankshop.result.ResultCode;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import lombok.extern.slf4j.Slf4j;
import org.bouncycastle.cert.ocsp.Req;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.List;
import java.util.Map;


@RestController
@RequestMapping("/api/v1/order")
@Slf4j
public class OrdersController {
    @Autowired
    OrderService orderService ;
    @Autowired
    UserService userService ;
    @Autowired
    GoodsService goodsService ;
    @Autowired
    LogisticsService logisticsService ;

    private static final String PAGE_REQUEST_KEY = "pageRequest" ;
    private static final String PARAMETER_KEY = "parameter" ;
    private static final String ASSESS_PARAMETER_KEY = "assessParameter" ;
    private static final String ASSESS_TYPE_KEY = "assessType" ;
    private static final String ASSESS_TIME_KEY = "assessTime" ;
    private static final String ASSESS_GOOD_ID_KEY  = "goodsId" ;
    private static final String DEPARTMENT_KEY = "department" ;
    private static final String GOODSPHOTO_KEY = "goodsPhoto" ;

    private static final String DELIVERY_MODE = "快递公司" ;
    private static final String SEPARATOR_COMMA = "," ;
    private static final String SEPARATOR_SEMICOLON = "：" ;

    @RequestMapping(value = "/find_assess_by_goodId",method = RequestMethod.POST)
    public Object findAssessByGoodId(@RequestBody JSONObject jsonParam){

        PageRequest pageRequest = JSON.parseObject(jsonParam.getJSONObject(PAGE_REQUEST_KEY).toJSONString(), PageRequest.class) ;
        JSONObject param = jsonParam.getJSONObject(ASSESS_PARAMETER_KEY) ;

        Result result ;
        try{
            String assessType = param.getString(ASSESS_TYPE_KEY) ;
            String assessTime = param.getString(ASSESS_TIME_KEY) ;
            Long assessGoodsId = param.getLong(ASSESS_GOOD_ID_KEY) ;
            result = Result.success() ;
            PageResult pageResult = orderService.getOrderAssessList(pageRequest,assessType,assessGoodsId,assessTime) ;
            List<?> list =  pageResult.getContent() ;
            list.stream().forEach((item)->{
                BuOrderAssess orderAssess = (BuOrderAssess)item ;
                Map<String,Object> map  ;
                Object jsonObject = userService.findUserInfoByUserId(orderAssess.getUserId()) ;
                if( jsonObject != null ){
                    map = (Map<String,Object>) jsonObject ;
                    orderAssess.setUserName((String) map.get(DEPARTMENT_KEY));
                }
            });
            pageResult.setContent(list);
            result.setData(pageResult);
        }catch (Exception e) {
            result = Result.failed(ResultCode.SYSTEM_EXECUTION_ERROR) ;
            log.info(" error : {} ",e);
        }
        return result ;
    }

    @RequestMapping(value = "find_assess_count_by_goodId",method = RequestMethod.GET)
    public Object findAssessCountByGoodId(Long goodId , String assessTime){

        Result result ;
        try{
            result = Result.success() ;
            Map<String,Integer> assessCountMap = orderService.getAssessCountByGoodId(goodId, assessTime) ;
            result.setData(assessCountMap);
        }catch (Exception e) {
            result = Result.failed(ResultCode.SYSTEM_EXECUTION_ERROR) ;
            log.info(" error : {} ",e);
        }

        return result ;
    }

    @RequestMapping(value = "find_orders_by_userId" ,method = RequestMethod.POST)
    public Object findOrdersByUserId(@RequestBody JSONObject json){
        Result result ;
        PageRequest pageRequest = JSON.parseObject(json.getJSONObject(PAGE_REQUEST_KEY).toJSONString(), PageRequest.class) ;
        JSONObject parameter = json.getJSONObject(PARAMETER_KEY) ;
        log.info(parameter.toJSONString());
        try {
            result = Result.success() ;
            PageResult pageResult = orderService.findOrdersGROUPByOrderNo(pageRequest,parameter) ;
            result.setData(pageResult);

        }catch (Exception e){
            result = Result.failed(ResultCode.SYSTEM_EXECUTION_ERROR) ;
            log.info("error : {} " , e);
        }

        return result ;
    }

    @RequestMapping(value = "find_orders_by_accountNo",method = RequestMethod.GET)
    public Object findOrdersByaccountNo(Long userId ,String accountNo ){
        Result result ;
        try {

            result = Result.success() ;
            List<BuOrder> orders = orderService.findOrdersByaccountNo(userId,accountNo);
            result.setData(orders);

        }catch (Exception e){
            result = Result.failed(ResultCode.SYSTEM_EXECUTION_ERROR) ;
            log.info("error : {} " , e);
        }

        return result ;
    }

    /**
     * 对账管理
     * @param json
     * @return
     */
    @RequestMapping(value = "find_reconciliations", method = RequestMethod.POST)
    public Object findReconciliations(@RequestBody JSONObject json){
        Result result ;
        PageRequest pageRequest = JSON.parseObject(json.getJSONObject(PAGE_REQUEST_KEY).toJSONString(), PageRequest.class) ;
        JSONObject parameter = json.getJSONObject(PARAMETER_KEY) ;
        log.info(parameter.toJSONString());
        try {
            result = Result.success() ;
            PageResult pageResult = orderService.reconciliation(pageRequest,parameter) ;
            result.setData(pageResult);

        }catch (Exception e){
            result = Result.failed(ResultCode.SYSTEM_EXECUTION_ERROR) ;
            log.info("error : {} " , e);
        }
        return result ;
    }
    @RequestMapping(value = "find_reconciliation_by_status",method = RequestMethod.POST)
    public Object findReconciliationByStatus(@RequestBody JSONObject json){
        Result result ;
        try {
            result = Result.success() ;
            JSONObject parameter = json.getJSONObject(PARAMETER_KEY) ;
            Map<String,Object> paremer =  parameter; ;

            Map<String,Integer> map = orderService.findReconciliationByStatus(paremer) ;
            result.setData(map);
        }catch (Exception e){
            result = Result.failed(ResultCode.SYSTEM_EXECUTION_ERROR) ;
            log.info("error : {} " , e);
        }
        return result ;
    }
    /**
     *
     * @param timeType
     * @param userId
     * @param keyword
     * @return
     */
    @RequestMapping(value = "find_orders_by_status",method = RequestMethod.GET)
    public Object findOrdersByStatus(String timeType,Long userId,String keyword){
        Result result ;
        try {
            result = Result.success() ;
            HashMap<String,Object> paremer = new HashMap<>() ;
            paremer.put("timeType",timeType) ;
            paremer.put("userId",userId) ;
            paremer.put("keyword",keyword);

            log.info(JSON.toJSONString(paremer));
            Map<String,Integer> map = orderService.findOrdersByStatus(paremer) ;
            result.setData(map);
        }catch (Exception e){
            result = Result.failed(ResultCode.SYSTEM_EXECUTION_ERROR) ;
            log.info("error : {} " , e);
        }
        return result ;
    }

    /**
     * 更新订单表中的图片
     * @return
     */
    @RequestMapping(value = "update_Good_Picture" ,method = RequestMethod.GET)
    public Object updateGoodPicture(){
        Result result ;
        try {
            result = Result.success() ;
            List<BuOrder> buOrders = orderService.findAllOrders() ;
            if(!buOrders.isEmpty()){
                buOrders.forEach((item)->{
                    JSONObject goods = goodsService.findById(item.getGoodsId()) ;
                    log.info(JSON.toJSONString(goods));
                    orderService.updateGoodPicture(item.getGoodsId(),goods.getString(GOODSPHOTO_KEY));
                });
            }
        }catch (Exception e){
            result = Result.failed(ResultCode.SYSTEM_EXECUTION_ERROR) ;
            log.info("error : {} " , e);
        }
        return result ;
    }

    /**
     * 根据订单号获取订单
     * @param orderNo
     * @return
     */
    @RequestMapping(value = "find_order_by_no",method = RequestMethod.GET)
    public Object findOrderByNo(String  orderNo){
        Result result  ;
        try {
            result = Result.success() ;
            List<BuOrder> orders = orderService.findOrderByNo(orderNo) ;
            orders.get(0).setAddress(logisticsService.getGoodsAddress(orders.get(0).getAddressId()));
            result.setData(orders);

        }catch (Exception e){
            result = Result.failed(ResultCode.SYSTEM_EXECUTION_ERROR) ;
            log.info("error : {} " , e);
        }

        return result ;
    }

    @RequestMapping(value = "find_recent_orders" , method = RequestMethod.GET)
    public Object findRecentOrders(Long userId){
        Result result  ;
        try {
            result = Result.success() ;
            List<BuOrder> orders = orderService.findRecentOrder(userId) ;
            orders.get(0).setAddress(logisticsService.getGoodsAddress(orders.get(0).getAddressId()));
            result.setData(orders);

        }catch (Exception e){
            result = Result.failed(ResultCode.SYSTEM_EXECUTION_ERROR) ;
            log.info("error : {} " , e);
        }

        return result ;
    }
    /**
     * 根据订单id获取物流信息
     * @param orderId
     * @return
     */
    @RequestMapping(value = "find_logistics_by_no",method = RequestMethod.GET)
    public Object findLogisticsByNo(Long orderId){
        Result<JSONObject> result  ;
        JSONObject logisticsInfo = new JSONObject() ;
        try {
            result = Result.success() ;
            List<BuOrderTransactRecord> records =  logisticsService.findLogisticsByNo(orderId) ;

            if(!records.isEmpty()){
                BuOrderTransactRecord record = records.get(0) ;
                String remark = record.getRemark() ;
                String[] remarks = remark.split(SEPARATOR_COMMA) ;

                if(remarks.length>0){
                    //快递物流
                    if(remarks[0].split(SEPARATOR_SEMICOLON)[0].equals(DELIVERY_MODE)){
                        String logisticsNo = remarks[1].split(SEPARATOR_SEMICOLON)[1] ;
                        String logisticsCompany = remarks[0].split(SEPARATOR_SEMICOLON)[1] ;
                        logisticsInfo.put("deliveryMode","express");
                        logisticsInfo.put("logisticsNo",logisticsNo) ;
                        logisticsInfo.put("logisticsCompany",logisticsCompany) ;
                        LogisticsRemote logisticsRemote = new LogisticsRemote() ;
                        String ShipperCode = logisticsService.getOrderShipper(logisticsCompany).getShipperCode() ;
                        String  traces =  logisticsRemote.getOrderTracesByJson( ShipperCode , logisticsNo);
                        JSONObject tracesJson = JSON.parseObject(traces) ;
                        log.info(tracesJson.toJSONString());
                        logisticsInfo.put("traces", tracesJson.getJSONArray("Traces")) ;

                    }else{ //线下
                        //配送员姓名：郑琪伟,联系电话：13336052229
                        String deliveryMan = remarks[0].split(SEPARATOR_SEMICOLON)[1] ;
                        String deliveryPhone = remarks[1].split(SEPARATOR_SEMICOLON)[1] ;
                        logisticsInfo.put("deliveryMode","offlineDistribution");
                        logisticsInfo.put("deliveryMan",deliveryMan) ;
                        logisticsInfo.put("deliveryPhone",deliveryPhone) ;
                    }
                }
            }else{
                logisticsInfo.put("info","no") ;
            }
        }catch (Exception e){
            result = Result.failed(ResultCode.SYSTEM_EXECUTION_ERROR) ;
            log.info("error : {} " , e);
        }
        result.setData(logisticsInfo);
        return result ;
    }


}
